<?php

namespace Yjius\fileshandler\local;

use Yjius\fileshandler\FilesHandlerBuilderInterface;

class LocalBuilder implements FilesHandlerBuilderInterface
{
    static private $instance;

    private function __construct($params)
    {

    }

    private function __clone()
    {

    }

    //单例模式
    static public function getInstance($params)
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     * Purpose: 本地上传 此处等于本地文件保存本地文件
     * Author:yingjiusheng@gsdata.cn
     * @date 2021/11/24 15:17
     * $localFilePath = $_FILE['tmp_name']
     */
    public function uploadOneFile($fileObject, $localFile, $options = NULL)
    {
        if (is_uploaded_file($localFile['tmp_name'])) {
            if (move_uploaded_file($localFile['tmp_name'], $fileObject)) {
                return str_replace('\\', DIRECTORY_SEPARATOR, $fileObject);
            }
            throw new \Exception('上传失败');
        }
        throw new \Exception('不是本地上传文件类型');
    }

    /**
     * 批量删除oss文件
     */
    public function deleteFiles($files = [])
    {
        if (!empty($files)) {
            foreach ($files as $file) {
                @unlink($file);
            }
            return true;
        }
        return false;
    }


    /**
     * Purpose: 本地大文件分片上传方法三连
     * @date 2021/11/25 11:31
     */
    public function checkFile($fileInfo, $tmpDir = '', $saveDir = '')
    {
        $up = new UploadHelper();
        if (!empty($tmpDir)) {
            $up->setTmpDir($tmpDir);
        }
        if (!empty($saveDir)) {
            $up->setSaveDir($saveDir);
        }
        $up->fileInfo = $fileInfo;
        return $up->checkFile();
    }

    /**
     * Purpose: 本地大文件分片上传方法三连
     * @date 2021/11/25 11:31
     */
    public function upload($fileInfo, $tmpDir = '', $saveDir = '')
    {
        $up = new UploadHelper();
        if (!empty($tmpDir)) {
            $up->setTmpDir($tmpDir);
        }
        if (!empty($saveDir)) {
            $up->setSaveDir($saveDir);
        }
        $up->fileInfo = $fileInfo;
        return $up->upload();
    }

    /**
     * Purpose: 本地大文件分片上传方法三连
     * @date 2021/11/25 11:31
     */
    public function merge($fileInfo, $tmpDir = '', $saveDir = '')
    {
        $up = new UploadHelper();
        if (!empty($tmpDir)) {
            $up->setTmpDir($tmpDir);
        }
        if (!empty($saveDir)) {
            $up->setSaveDir($saveDir);
        }
        $up->fileInfo = $fileInfo;
        return $up->merge();
    }

    public function getPolicy()
    {
        throw new \Exception('本地上传不支持此方法');
    }

    public function getSignUrl($object, $timeout = 3600)
    {
        throw new \Exception('本地上传不支持此方法');
    }

    public function getRangeObject($object, $range = '0-4')
    {
        throw new \Exception('本地上传不支持此方法');
    }

}